﻿using System;
using System.Diagnostics.Contracts;
using System.Linq;
using Adalbertus.BudgetPlanner.Domain;
using Caliburn.Micro;

namespace Adalbertus.BudgetPlanner.ViewModels.ExternalSources
{
    public class SavingVM : UnitOfWorkVM
    {
        private Saving _wrappedSaving;
        public Saving WrappedSaving
        {
            get
            {
                Contract.Ensures(Contract.Result<Saving>() != null);
                return _wrappedSaving;
            }
        }

        public SavingVM(Saving saving)
        {
            Contract.Requires<ArgumentNullException>(saving != null);
            _wrappedSaving = saving;
            _entries = new BindableCollection<SavingEntryVM>();
            _entries.AddRange(_wrappedSaving.Entries.Select(x => new SavingEntryVM(x, this)));
            foreach (SavingEntryVM entry in _entries)
            {
                entry.PropertyChanged += SavingEntryPropertyChanged;
            }
        }

        public string Name
        {
            get { return _wrappedSaving.Name; }
            set
            {
                _wrappedSaving.Name = value;
                NotifyOfPropertyChange(() => Name);
            }
        }

        private BindableCollection<SavingEntryVM> _entries;
        public BindableCollection<SavingEntryVM> Entries
        {
            get
            {
                Contract.Ensures(Contract.Result<BindableCollection<SavingEntryVM>>() != null);
                return _entries;
            }
        }

        internal void AddEntry(SavingEntry savingEntry)
        {
            Contract.Requires<ArgumentNullException>(savingEntry != null);

            SavingEntryVM entryVm = new SavingEntryVM(savingEntry, this);
            entryVm.PropertyChanged += SavingEntryPropertyChanged;
            Entries.Add(entryVm);
        }

        internal void RemoveEntry(SavingEntryVM savingEntry)
        {
            Contract.Requires<ArgumentNullException>(savingEntry != null);

            Entries.Remove(savingEntry);
            savingEntry.PropertyChanged -= SavingEntryPropertyChanged;
        }

        private void SavingEntryPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            NotifyOfPropertyChange(() => Entries);   
        }
    }
}
